// 获取经期周期信息云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const userId = wxContext.OPENID
  
  try {
    const { year, month } = event
    
    console.log('获取经期周期信息:', {
      userId,
      year,
      month
    })

    // 获取指定月份的经期周期
    const cycleResult = await db.collection('period_cycles')
      .where({
        user_id: userId,
        year: year,
        month: month
      })
      .get()

    if (cycleResult.data.length > 0) {
      const cycleData = cycleResult.data[0]
      
      console.log('找到经期周期数据:', cycleData)
      
      return {
        status: 'success',
        data: {
          hasCycle: true,
          startDate: cycleData.start_date,
          periodDates: cycleData.period_dates,
          year: cycleData.year,
          month: cycleData.month
        }
      }
    } else {
      console.log('未找到经期周期数据')
      
      return {
        status: 'success',
        data: {
          hasCycle: false,
          startDate: null,
          periodDates: [],
          year: year,
          month: month
        }
      }
    }

  } catch (error) {
    console.error('获取经期周期失败:', error)
    return {
      status: 'error',
      message: '获取经期周期失败',
      error: error.message
    }
  }
}
